package com.wsc.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wsc.goods.domain.BrandPo;
import com.wsc.goods.service.BrandService;
import com.wsc.tools.AjaxResult;
import com.wsc.tools.PageQuery;
import com.wsc.tools.PageResult;
import com.wsc.tools.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品品牌管理
 */
@RestController
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    /**
     * 查询
     * @param pageQuery 查询参数
     * @return 查询结果
     */
    @PostMapping("/find")
    public PageResult<BrandPo> query(@RequestBody PageQuery pageQuery){
        IPage<BrandPo> iPage =  brandService.page(new Page<BrandPo>(pageQuery.getPage(),pageQuery.getRows()),new QueryWrapper<BrandPo>().like("name",pageQuery.getKeywords()
        ).or().like("englishName",pageQuery.getKeywords()).orderByDesc("createTime"));
        return new PageResult<BrandPo>(iPage.getTotal(),iPage.getRecords());
    }

    /**
     * 新增和修改品牌
     * @param brandPo 品牌实体
     * @return 修改结果
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody BrandPo brandPo){
        try {
            if(brandPo.getId() == null) {
                brandPo.setCreateTime(System.currentTimeMillis());
                brandService.save(brandPo);
            }
            else {
                brandPo.setUpdateTime(System.currentTimeMillis());
                brandService.updateById(brandPo);
            }
            return AjaxResult.getInstance().setMsg("保存成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.getInstance().setMsg("保存失败").setCode(500);
        }
    }

    @GetMapping("/delBrand/{ids}")
    public AjaxResult delBrand(@PathVariable("ids") String ids){
        List<Long> arrs = StrUtils.splitStr2LongArr(ids);
       try {
            brandService.removeByIds(arrs);
            return AjaxResult.getInstance().setMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.getInstance().setCode(500).setMsg("删除失败");
        }

    }

}
